package com.kaka.bus.engine.borrow.phone;

import android.content.Intent;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jakewharton.rxbinding.view.RxView;
import com.kaka.bus.R;
import com.kaka.bus.api.Api;
import com.kaka.bus.api.RetrofitUtils;
import com.kaka.bus.base.RxBaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.borrow.pact.PactGreementActivity;
import com.kaka.bus.engine.home.main.limit.LimitActivity;
import com.kaka.bus.engine.other.DrainageActivity;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.util.U;
import com.kaka.bus.util.logger.Logger;
import com.kaka.bus.view.dialog.GifDialog;
import com.kaka.bus.view.dialog.MessageDialog;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.disposables.CompositeDisposable;

/**
 * 作者：张琦 on 2016/10/15 23:07
 */

public class PhoneActivity extends RxBaseActivity {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_phone_phone)
    TextView mTvPhonePhone;
    @BindView(R.id.tv_phone_yunying)
    TextView mTvPhoneYunying;
    @BindView(R.id.edt_phone_service)
    EditText mEdtPhoneService;
    @BindView(R.id.tv_phone_forget)
    TextView mTvPhoneForget;
    @BindView(R.id.cb_phone_cb)
    CheckBox mCbPhoneCb;
    @BindView(R.id.tv_phone_tips)
    TextView mTvPhoneTips;
    @BindView(R.id.btn_phone_next)
    AppCompatButton mBtnPhoneNext;
    private String mPhone;
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    public static final String PHONE = "phone";
    public static final String ID = "id";
    private String mYunying;
    private GifDialog mGifDialog;
    private MessageDialog mDialog;

    private String mLingshi;

    @Override
    protected void initView() {
        mToolbarName.setText("手机认证");
        mToolbarBack.setOnClickListener(v -> finish());
        mGifDialog = new GifDialog(this);
        mDialog = new MessageDialog(this);
    }

    /**
     * 是否已经提交过通讯录
     */
    @Override
    protected void initData() {
        mPhone = getUserInfo().getPhone();
        commitLocalContact();
        if (!TextUtils.isEmpty(mPhone)) {
            mTvPhonePhone.setText(mPhone);
            String yunying = U.execute(mPhone);
            mTvPhoneYunying.setText(getString(R.string.china) + yunying);
        }
    }

    @Override
    protected void initListener() {
        RxView.clicks(mBtnPhoneNext)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(v -> {
                    String service = mEdtPhoneService.getText().toString();
                    if (TextUtils.isEmpty(service)) {
                        showMessage(R.string.servicenotnull);
                    } else {
                        /**
                         * 信息收集授权协议 打钩
                         */
                        commitServicePwd();
                    }
                });

        mTvPhoneForget.setOnClickListener(v -> {
            Intent intent = new Intent(this, ForGetServiceActivity.class);
            intent.putExtra("yunying", mYunying);
            startActivity(intent);
        });

        mTvPhoneTips.setOnClickListener(v -> {
            Intent intent = new Intent(this, PactGreementActivity.class);
            intent.putExtra(PactGreementActivity.TYPE, PactGreementActivity.TYPE_LOAD_URL);
            intent.putExtra(PactGreementActivity.URL, Api.BASE_URL + "registerAccredit.html");
            intent.putExtra(PactGreementActivity.TITLE, "咔咔钱包服务与隐私协议");
            startActivity(intent);
        });
    }


    private void commitLocalContact() {
        String phone = getUserInfo().getPhone();
        if (!TextUtils.isEmpty(phone)) {
            mPhone = phone;
            mTvPhonePhone.setText(mPhone);
            mYunying = U.execute(phone);
            mTvPhoneYunying.setText(U.connectString(getString(R.string.china), mYunying));
        }
    }

    /**
     * 提交服务密码
     */
    private void commitServicePwd() {
        String service = mEdtPhoneService.getText().toString();
        showDialog("请稍等..");

        Map<String, String> map = new HashMap<>();
        map.put(Constant.USERID, getUserId());
        map.put("phone_pwd", service);
        map.put("token", getToken());
        mCompositeDisposable.add(RetrofitUtils.getInstance().build()
                .commitPhonePwdRc(map)
                .compose(T.D())
                .subscribeWith(new Result<HttpWrapper<String>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<String> data) {
                        switchResult(data);
                    }

                    @Override
                    protected void onFinish() {
                        dissDialog();
                    }
                }));
    }

    private void switchResult(HttpWrapper<String> bean) {
        Logger.i(bean.code + "张琦" + new Gson().toJson(bean));
        switch (bean.getCode()) {
            case "8888":
            case "0000":
            case "10008":
//                startActivity(new Intent(PhoneActivity.this, LimitActivity.class));
                commitstatus();
                break;
            case "1000":
                U.toDrainage(this, DrainageActivity.TYPE_REFUSE, Constant.REFUES);
                break;
            case "2000":
                /**
                 * 展示后台信息
                 */
                mDialog.show();
                mDialog.setMessage(bean.getInfo());
                break;
            case "10002":
                /**
                 * 跳验证码界面
                 */
                Intent intent = new Intent(this, PhoneYzmActivity.class);
                intent.putExtra(PHONE, mPhone);
                intent.putExtra(ID, bean.code);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
                break;
            case "10003":
                Intent intent2 = new Intent(this, PhoneYzmActivity2.class);
                intent2.putExtra(ID, bean.getCode());
                startActivity(intent2);
                finish();
                break;
            case "10022":
                Intent intent1 = new Intent(this, PhoneYzmActivity.class);
                intent1.putExtra(PHONE, mPhone);
                intent1.putExtra(ID, bean.code);
                intent1.putExtra("type", "2");
                startActivity(intent1);
                finish();
                overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
                break;
            case Constant.TOKEN_TIMEOUT:
                U.tokenOut(this);
                break;
            default:
                showMessage(bean.getInfo());
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }

    @Override
    protected boolean needFullScreen() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_phone;
    }

    /**
     * 提交状态
     */
    private void commitstatus() {
        mCompositeDisposable.add(RetrofitUtils.getInstance().build()
                .NodeOk(getUserId(), getToken())
                .compose(T.D())
                .subscribeWith(new Result<HttpWrapper<String>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<String> data) {
                        startActivity(new Intent(PhoneActivity.this, LimitActivity.class));
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        startActivity(new Intent(PhoneActivity.this, LimitActivity.class));
                    }

                    @Override
                    protected void onFinish() {
                        dissDialog();
                    }
                }));
    }
}
